package com.jiangxjsy.admin.service.impl;

import com.jiangxjsy.admin.mapper.AdminMessageMapper;
import com.jiangxjsy.admin.property.JwtProperty;
import com.jiangxjsy.admin.service.AdminMessageService;
import com.jiangxjsy.core.constant.BasicConstant;
import com.jiangxjsy.core.exception.AuthorizationException;
import com.jiangxjsy.core.jwt.JwtCore;
import com.jiangxjsy.core.wrap.ResultCode;
import com.jiangxjsy.model.admin.vo.AdminMessageVO;
import com.jiangxjsy.model.core.entity.UserMeta;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;

/**
 * wukong-crm-master
 * 蒋胜宇
 * 2025/6/6 16:53
 */

@Service
public class AdminMessageServiceImpl implements AdminMessageService {
    @Resource
    private AdminMessageMapper adminMessageMapper;

    @Resource
    private JwtProperty jwtProperty;

    /**
     * 查询未读消息数量
     *
     * @param request 请求
     * @param response 响应
     * @return 未读消息数量
     */
    @Override
    public AdminMessageVO queryUnreadCount(HttpServletRequest request, HttpServletResponse response) {
        String token = request.getHeader(BasicConstant.TOKEN_NAME);
        UserMeta userMeta;
        try {
            userMeta = new JwtCore<>(UserMeta.class).analyzeToken(token, jwtProperty.getPublicKey());
        } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException | InstantiationException e) {
            throw new AuthorizationException(ResultCode.AuthorizationResultCode.AUTHORIZATION_LOGIN_ERR);
        }
        Long userId = userMeta.getUserId();

        return adminMessageMapper.selectUnreadCount(userId);
    }
}
